/*
 * mapBinary.java
 *
 * Copyright (C) 2008 Paul Nettleship
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 */
package staticTrailExplorer;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

/**
 *
 * @author codebauer
 */
class mapBinary implements mapDataIF
   {
   private File inputPhile = null;
   private DataOutputStream outputStream = null;
   private tileMap map;
   private static long lastTileOffset=0;
   ByteArrayOutputStream byteStream;
  
   public void init(tileMap map)
      {
      this.map = map;
      map.calibrated = true;
      }

   public void openInput(File phile) throws FileNotFoundException
      {
      inputPhile = phile;
      }

   public void openOutput(File phile) throws FileNotFoundException
      {
      outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(phile)));
      }

   public void close() throws IOException
      {
      if(outputStream != null)
         outputStream.close();
      }

   public location getDefaultStartLocation()
      {
      return new location(0,0,location.maxZoom);
      }
   
   public BufferedImage loadMapTile(location loc)
      {
      synchronized (this)
         {
         String found = "";
         int size = 0;
         try
            {
            DataInputStream inputStream = new DataInputStream(new FileInputStream(inputPhile));
            while (found.equals(loc.getName(map)) != true)
               {
               inputStream.skipBytes(size);
               found = inputStream.readUTF();
               size = inputStream.readInt();
               }
            System.out.print("found="+found+" search="+loc.getName(map)+"\n");
            return ImageIO.read(inputStream);
            }
         catch (IOException ex)
            {
            System.out.print(ex);
            System.out.print("not found="+found+" search="+loc.getName(map)+"\n");
            return null;
            }
         }
      }

   /* This function is modified, It renders the bin file to MTE cache format
    * The File must be saved to "MTEFileCache" and can be exported to mobile phone.
    * This option enables to use the map without downloading it from the server.
    */
   public void saveMapTile(BufferedImage tile, location loc) throws IOException
      {
      if( tile != null )
         {
			           byteStream = new ByteArrayOutputStream();
				    ImageIO.write(tile, "png", byteStream);                  
				    // outputStream.writeUTF(loc.getName(map));
				    System.out.println(map.getMapData());
				    System.out.println(loc.getTileX(map));
				    System.out.println(loc.getTileY(map));
				    System.out.println(loc.getZoom());
				     
				    String url =  "http://b.tile.openstreetmap.org/"+loc.getZoom()+"/"+loc.getTileX(map)+"/"+loc.getTileY(map)+".png";
				    String cacheKey = "osmmaps-"+loc.getZoom()+"-"+loc.getTileX(map)+"-"+loc.getTileY(map);
				    outputStream.writeInt(loc.getTileX(map));
				    outputStream.writeInt(loc.getTileY(map));
				    outputStream.writeInt(loc.getZoom());
				    
				    outputStream.writeUTF(url);
				   
				    outputStream.writeUTF(cacheKey);
				    System.out.println("Offset value writing : "+lastTileOffset );
				    outputStream.writeLong(lastTileOffset);
				    //writeUtf writes
				    lastTileOffset+=12+
				    2+url.getBytes().length+
				    2+cacheKey.getBytes().length+
				    8+
				    4+
				    byteStream.toByteArray().length;
				    
				    outputStream.writeInt(byteStream.toByteArray().length);
				    outputStream.write(byteStream.toByteArray());
				    outputStream.flush();
		
          }
      //not important just for testing the file format
   //   readMapTile();
      }

   public void setCalibration()
      {
      String text = "Can not calibrate. " + map.name + " already calibarated.\n";
      text += "Try selecting another window!";
      JOptionPane.showMessageDialog(null,text,"Warning",JOptionPane.PLAIN_MESSAGE);
      }
   // temp method for testing the Cache file format .
      public void readMapTile()
   {
      // DataOutputStream dreadMapTileos = new DataOutputStream();
       try{
       DataInputStream is = null;
       is = new DataInputStream(new FileInputStream("/home/raghul/test"));
       
       while (true) { // exception deals catches EOF
        int x  = is.readInt();
        int y  = is.readInt();
        int z  = is.readInt();
        String url  = is.readUTF();
        String cachekey = is.readUTF();
        
        int te = is.readInt();
        System.out.println(x+"  "+y+" "+z+" "+url+" "+cachekey+ " "+te);
        int arrayLength = is.readInt();
        byte [] imageByteArray = new byte[arrayLength];
        is.read(imageByteArray, 0, arrayLength);
        ImageIO.createImageInputStream(imageByteArray);
        System.out.println(arrayLength);
        System.out.println(imageByteArray.length);
        
       // System.out.print((char) ch);
        System.out.flush();
        is.close();
      }
      
       }catch(Exception e){System.out.println("thapu "+e);}
   }
   }